import React, { Component } from 'react';
import 'antd/dist/antd.css';
import store from './store';
import { getInputChangeAciton, getAddItemAciton, getDeleteItemAciton, getInitListAction } from './store/actionCreator';
import TodoListUI from './TodoListUI';

class TodoListSaga extends Component {

  constructor(props) {
    super(props);
    this.state = store.getState();
    // console.log(this.state);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleStoreChange = this.handleStoreChange.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleItemDelete = this.handleItemDelete.bind(this);
    store.subscribe(this.handleStoreChange); //只要store发生改变，就会执行
  }

  render() {
    return (
      <TodoListUI
        handleInputChange = {this.handleInputChange}
        inputValue = {this.state.inputValue}
        handleBtnClick = {this.handleBtnClick}
        list = {this.state.list}
        handleItemDelete = {this.handleItemDelete}
      />
    )
  }

  componentDidMount() {
    const action = getInitListAction();
    store.dispatch(action);
  }

  handleInputChange(e) {
    const action = getInputChangeAciton(e.target.value);
    store.dispatch(action);
  }

  handleBtnClick() {
    const action = getAddItemAciton();
    store.dispatch(action)
  }

  handleItemDelete(index) {
    const action = getDeleteItemAciton(index);
    store.dispatch(action)
  }

  handleStoreChange() {
    this.setState(store.getState())
  }

}

export default TodoListSaga;